<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>监听路由</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
</head>

<body>
    <div id='app'>
        <router-view></router-view>
    </div>
    <script>
        const list = {
            template:'<div>列表界面</div>'
        }

        const detail = {
            template: `<div>军事新闻,{{article.id}}
                    <router-link to="/detail/3">国际新闻</router-link>
                    <div @click="initData(6)">国内新闻</div>
                </div>`,
            data() {
                return {
                    article: {

                    }
                }
            },
            methods: {
                initData(id) {
                    this.$router.push('/detail/'+id)
                    setTimeout(() => {
                        // this.article.id = this.$route.params.id
                        this.article = {
                            id: id
                        }
                    }, 1000);
                }
            },
            created() {
                console.log(this.$route.params.id);
                // 根据id请求接口，拿到详情
                setTimeout(() => {
                    // this.article.id = this.$route.params.id
                    this.article = {
                        id: this.$route.params.id
                    }

                }, 1000);
            },
            watch: {
                $route(newVal, oldVal) {
                    console.log(this.$route.params.id);
                    // 根据id请求接口，拿到详情
                    setTimeout(() => {
                        // this.article.id = this.$route.params.id
                        this.article = {
                            id: this.$route.params.id
                        }

                    }, 1000);
                }
            },
        }

        const router = new VueRouter({
            routes: [{
                path: '/detail/:id',
                component: detail,
                meta:{
                    title:'详情'
                }
            },{
                path:'/list',
                component:list,
                // 路由的元数据，可以定义路由的基本信息
                meta:{
                    title:'列表'
                }
            }]
        })


        const vm = new Vue({
            el: '#app',
            data: {

            },
            router,
            // 监听器
            watch: {
                $route(){
                    // 设置标题
                    document.title = this.$route.meta.title
                }
            }
        })
    </script>
</body>

</html>